package com.token;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;


@Component
public class LoginRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
    /**
     * 管授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String tokenString = principals.toString();
        String username = JwtUtil.getUsername(tokenString);

        //查数据库，用户的权限，略
       /* authorizationInfo.addStringPermission("/api/searchDep");*/
        authorizationInfo.addStringPermission("/api/removeDep");
        return authorizationInfo;
    }

    /**
     * 管登录
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //JWTFilter传过来的令牌
        String tokenString = (String) token.getPrincipal();
        System.out.println(tokenString);
        //取用户名，如果为null则无效
        String username = JwtUtil.getUsername(tokenString);
        if (username==null)
        {
            throw new RuntimeException("令牌无效");
        }
        return new SimpleAuthenticationInfo(tokenString, tokenString, getName());

    }
}

